//
//  LoadingViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/5/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "LoadingViewController.h"

#import "HCTabbarViewController.h"
#import "MHNavigationController.h"

#import "EasyTakePicPresentChooserViewController.h"
#import "EasyTakePicPublishViewController.h"
#import "MainV2ViewController.h"
#import "EasyTakePicViewController.h"
#import "ConsulationV2ViewController.h"
#import "MyCenterViewController.h"

@interface LoadingViewController ()

@property (nonatomic, readwrite, strong) LoadingViewModel* viewModel;

@property (weak, nonatomic) IBOutlet UIView* testView;
@property (weak, nonatomic) IBOutlet UIImageView* imgView;
@property (weak, nonatomic) IBOutlet UIImageView* logo;

@end

@implementation LoadingViewController
@dynamic viewModel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    /// 初始化导航栏
    [self _setupNavigationItem];
    
    NSLog(@"ViewDidLoad TestView frame : %@", NSStringFromCGRect(self.testView.frame));
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    /// 初始化subView
    [self _setupSubViews];
    
    NSLog(@"DidLayoutSubviews TestView frame : %@", NSStringFromCGRect(self.testView.frame));
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"ViewWillAppear TestView frame : %@", NSStringFromCGRect(self.testView.frame));
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"ViewDidAppear TestView frame : %@", NSStringFromCGRect(self.testView.frame));
    
    [self judge2CallGeoCmd];
}

/// binding viewModel
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self);
    
    [[[[RACObserve(self.viewModel, isNetLinked) distinctUntilChanged] filter:^BOOL(id value) {

        return [value boolValue];
    }] deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self);

        [self _pushToMain];
    }];
    
    RACSignal* didEnterBgActiveNotifySignal = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] replay];
    RACSignal* didBecomeActiveNotifySignal = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] replay];
    
    [[didEnterBgActiveNotifySignal zipWith:didBecomeActiveNotifySignal] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self judge2CallGeoCmd];
    }];
}

#pragma mark - 设置导航栏
- (void)_setupNavigationItem
{
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = YES;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
}

#pragma mark - 初始化subView
- (void)_setupSubViews
{
    DataManager* dm = [DataManager sharedDataManager];
    
    NSString* strLoadingAdImgPath = [dm loadingAdImgFileUrl];
    
    if (strLoadingAdImgPath && [strLoadingAdImgPath isNotBlank])
    {
        self.logo.hidden = YES;
        self.imgView.hidden = NO;
        
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString* fileSavePath = [documentsDirectory stringByAppendingPathComponent:strLoadingAdImgPath];
        
        UIImage *img = [UIImage imageWithContentsOfFile:fileSavePath];
        [self.imgView setImage:img];
    }
    else
    {
        self.logo.hidden = NO;
        self.imgView.hidden = YES;
    }
}

#pragma mark - 替换RootViewController
- (void)_pushToMain
{
    HCTabbarViewController* tabbarVC = [[HCTabbarViewController alloc] init];
    
    MainV2ViewModel* mainVM = [[MainV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"首页"}];
    MainV2ViewController* mainVC = [[MainV2ViewController alloc] initWithViewModel:mainVM];
    MHNavigationController* mainNav = [[MHNavigationController alloc] initWithRootViewController:mainVC];
    
    EasyTakePicViewModel* etpVM = [[EasyTakePicViewModel alloc] initWithParams:@{}];
    EasyTakePicViewController* etpVC = [[EasyTakePicViewController alloc] initWithViewModel:etpVM];
    MHNavigationController* etpNav = [[MHNavigationController alloc] initWithRootViewController:etpVC];
    
    //占位
    UIViewController* placeHolderVC = [[UIViewController alloc] init];
    MHNavigationController* placeHolderNav = [[MHNavigationController alloc] initWithRootViewController:placeHolderVC];
    
    ConsulationV2ViewModel* consultationVM = [[ConsulationV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"环保咨询"}];
    ConsulationV2ViewController* consultationVC = [[ConsulationV2ViewController alloc] initWithViewModel:consultationVM];
    MHNavigationController* consultationNav = [[MHNavigationController alloc] initWithRootViewController:consultationVC];
    
    MyCenterViewModel* userCenterVM = [[MyCenterViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"个人中心"}];
    MyCenterViewController* userCenterVC = [[MyCenterViewController alloc] initWithViewModel:userCenterVM];
    MHNavigationController* userCenterNav = [[MHNavigationController alloc] initWithRootViewController:userCenterVC];
    
    tabbarVC.viewControllers = @[mainNav, etpNav, placeHolderNav, consultationNav, userCenterNav];
    
    __block HCTabbarViewController* weakTabbarVC = tabbarVC;
    tabbarVC.centerBtnBlock = ^(id btn)
    {
        //弹出中间选择
//        EasyTakePicPresentChooserViewModel* vm = [[EasyTakePicPresentChooserViewModel alloc] initWithParams:@{}];
//        EasyTakePicPresentChooserViewController* vc = [[EasyTakePicPresentChooserViewController alloc] initWithViewModel:vm];
        
//        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//        vc.view.backgroundColor = [UIColor clearColor];
//
//        [weakTabbarVC presentViewController:vc animated:YES completion:^{
//
//        }];
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        if ([um isLogined])
        {
            EasyTakePicPublishViewModel* vm = [[EasyTakePicPublishViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"生态行动（随手拍）"}];
            vm.isShowCamera = YES;
            EasyTakePicPublishViewController* vc = [[EasyTakePicPublishViewController alloc] initWithViewModel:vm];
            
            MHNavigationController* navc = [[MHNavigationController alloc] initWithRootViewController:vc];
            
            [[UIViewController getCurrentVC] presentViewController:navc animated:NO completion:^{
                
            }];
        }
        else
        {
            [MBProgressHUD mh_showTips:@"请登录后操作"];
        }
    };
    
//    CGSize selectionIndicatorImgSize = (CGSize) {tabbarVC.tabBar.bounds.size.width / tabbarVC.viewControllers.count, tabbarVC.tabBar.bounds.size.height};
//    tabbarVC.tabBar.selectionIndicatorImage = [UIImage mh_getImageWithColor:[UIColor colorWithHexString:@"#24b206"] size:selectionIndicatorImgSize];
    
    tabbarVC.tabBar.tintColor = Color_MainGreen;
    
    [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
    
    tabbarVC.modalPresentationStyle = UIModalPresentationCurrentContext;
    
    [AppDelegate sharedDelegate].window.rootViewController = tabbarVC;
}

- (void)judge2CallGeoCmd
{
    @weakify(self);
    
    if (!self.viewModel.isOpenLocation)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"打开定位开关" message:@"打开定位开关" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action)
        {
            @strongify(self)
            
            [self judge2CallGeoCmd];
        }];
        
        [alert addAction:setAction];
        [alert addAction:cancelAction];
        
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
        
        // 展示警告控制器
        [self presentViewController:alert animated:YES completion:nil];
    }
    else
    {
        [self.viewModel.reqGeoCmd execute:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
